package com.mhwx.mhlive.ui.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.cnlive.libs.util.chat.ChatUtil;
import com.cnlive.libs.util.chat.base.IChat;
import com.cnlive.libs.util.chat.model.CNMessage;
import com.mhwx.mhlive.R;
import com.mhwx.mhlive.bean.CNMessageInfo;
import com.mhwx.mhlive.model.CNMessageModole;
import com.mhwx.mhlive.ui.adapter.ChatListAdapter;
import com.mhwx.mhlive.ui.base.BaseFragment;
import com.mhwx.mhlive.util.ToStringUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;

import static android.content.ContentValues.TAG;

/**
 * 类功能描述
 * 医疗类聊天
 * @author Guol
 * @version 1.0
 * @copyright 北京明华维新信息技术有限公司
 * @time 2017/5/5
 */
public class MediacChatFragment extends BaseFragment implements View.OnClickListener{
    
    
    @BindView(R.id.chat_list_viewOne)
    RecyclerView mChatList;
    
    @BindView(R.id.message_content)
    EditText mMessage;
    
    @BindView(R.id.send_messageOne)
    Button mSend;

    private  int type;
    public static String TABLAYOUT_FRAGMENT = "tab_fragment";
    private String roomIdOne = "ChatRoom05";
    private Handler mHandler;
    private ArrayList<CNMessageInfo> groupChatOneListMy;
    private int i = 0;
    public String user_name_string="C丶c";
    public String user_id_string="1234567";
    private ChatListAdapter chatListAdapterOne;
    @Override
    protected int getLayoutRes() {
        return R.layout.frg_medical_chat;
    }
    public static MediacChatFragment newInstance(int type){
        MediacChatFragment fragment = new MediacChatFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(TABLAYOUT_FRAGMENT, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //设置监听

        init();
    }
    
    private void init(){
        mHandler = new Handler();
        groupChatOneListMy = new ArrayList<>();

//        ChatUtil.logOut(connectListener);

        chatListAdapterOne = new ChatListAdapter(getContext(),groupChatOneListMy);


//        if (user_name_string != null)
//            ChatUtil.login(new CNUserInfo(user_id_string, user_name_string, ""), connectListener);
//        else
        //加入聊天室
        ChatUtil.joinChatRoom(roomIdOne, -1, onOperationListener);
        //连接状态
        ChatUtil.setConnectStatusListener(connectStatusListener);
        //接收信息
        ChatUtil.setOnReceiveMessageListener(receiveMessageListener);
        mChatList.setAdapter(chatListAdapterOne);
        mSend.setOnClickListener(this);
    }



    // 加入聊天室监听
    private IChat.OnOperationListener onOperationListener = new IChat.OnOperationListener() {
        @Override
        public void onSuccess(int what, final String extra) {
            Log.v(TAG, +what + extra);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (i == 0) {
                        String objToJsonString = ToStringUtils.objToJsonString(new CNMessageModole(user_name_string + "加入聊天室", "2"));
                        ChatUtil.sendMessage(IChat.CHATROOM, roomIdOne, objToJsonString, sendMessageListener);
                        ++i;
                    }
                    Toast.makeText(getContext(), extra, Toast.LENGTH_SHORT).show();
                }
            });
        }
        @Override
        public void onError(int what, String extra) {
            Log.v(TAG, "加入聊天室" + what + extra);
        }
    };
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //向聊天室1发送消息
            case R.id.send_messageOne:
                //发送聊天室消息
                if (mMessage.getText().toString().isEmpty()) {
                    Toast.makeText(getContext(), "不能发送空消息呦~", Toast.LENGTH_SHORT).show();
                } else {
                    String objToJsonString = ToStringUtils.objToJsonString(new CNMessageModole(mMessage.getText().toString(), "1"));
                    ChatUtil.sendMessage(IChat.CHATROOM, roomIdOne, objToJsonString, sendMessageListener);
                    mMessage.setText("");
                }
                break;

        }
    }

    /**
     * 发送消息监听
     */
    private IChat.OnSendMessageListener sendMessageListener = new IChat.OnSendMessageListener() {

        @Override
        public void onAttached(CNMessage cnMessage) {
            Log.v(TAG, "SendMessageListener onAttached" + cnMessage.getTargetId() + cnMessage.getUserInfo().getUserName());
        }

        @Override
        public void onSuccess(final CNMessage cnMessage) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (((String) new JSONObject(cnMessage.getContent()).get("type")).equals("2"))
                            return;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if ((roomIdOne).equals(cnMessage.getTargetId())) {
                        chatListAdapterOne.add(groupChatOneListMy.size(),new CNMessageInfo(cnMessage, true));
                        chatListAdapterOne.notifyDataSetChanged();
                    }

                }
            });

        }

        @Override
        public void onError(CNMessage cnMessage, int i, final String s) {
            Log.v(TAG, "SendMessageListener 失败 " + i + "    s" + s);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    };
    //连接状态监听
    private IChat.OnConnectStatusListener connectStatusListener = new IChat.OnConnectStatusListener() {
        @Override
        public void onConnectStatus(int i, String s) {
            Log.i(TAG, "连接状态监听" + i + "   " + s);
        }
    };
    //接收消息监听
    private IChat.OnReceiveMessageListener receiveMessageListener = new IChat.OnReceiveMessageListener() {
        @Override
        public void processMessage(final CNMessage cnMessage) {
            Log.v(TAG, "receiveMessageListener" + "   " + cnMessage.getTargetId() + "   " + cnMessage.getContent());

            mHandler.post(new Runnable() {
                @Override
                public void run() {

                    try {
                        JSONObject jsonObject = new JSONObject(cnMessage.getContent().toString());
                        String type = (String) jsonObject.get("type");
                        if ("2".equals(type)) {
                            Toast.makeText(getContext(), cnMessage.getUserInfo().getUserName() + "加入聊天室", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    {
                        chatListAdapterOne.add(groupChatOneListMy.size(),new CNMessageInfo(cnMessage, false));
                        chatListAdapterOne.notifyDataSetChanged();
                    }
                }
            });
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        ChatUtil.quitChatRoom(roomIdOne, onOperationListener);
    }
}
